package com.ontheroad.mysql.together.service;

import cn.modoumama.page.PageObject;
import cn.modoumama.service.base.impl.BaseServiceImpl;
import com.ontheroad.api.request.TogetherRequest;
import com.ontheroad.api.response.Response;
import com.ontheroad.api.response.TogetherCommentResponse;
import com.ontheroad.api.response.TogetherResponse;
import com.ontheroad.core.util.DateUtils;
import com.ontheroad.core.util.SpringUtils;
import com.ontheroad.leanCloud.event.PushToUserEvent;
import com.ontheroad.leanCloud.model.PushType;
import com.ontheroad.mysql.together.mapper.TogetherCommentMapper;
import com.ontheroad.mysql.together.mapper.TogetherMapper;
import com.ontheroad.together.model.TogetherCommentModel;
import com.ontheroad.together.model.TogetherModel;
import com.ontheroad.together.service.TogetherService;
import com.ontheroad.user.model.UserModel;
import com.ontheroad.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by Administrator on 2017/10/23.
 */
@Service
@Transactional
public class TogetherServiceImpl extends BaseServiceImpl<TogetherModel, Integer> implements TogetherService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private TogetherMapper mapper;
    @Autowired
    private TogetherCommentMapper commentMapper;
    @Autowired
    private UserService userService;

    @Autowired
    public void setMapper(TogetherMapper mapper) {
        setGenericMapper(mapper);
    }

    @Override
    public Response publish(TogetherRequest request) throws Exception {
        Response response = new Response();
        TogetherModel togetherModel = new TogetherModel();
        togetherModel.setCreateId(request.getUserId().intValue());
        togetherModel.setName(request.getName());
        togetherModel.setContent(request.getContent());
        togetherModel.setImages(request.getImages());
        togetherModel.setAddress(request.getAddress());
        togetherModel.setStartTime(DateUtils.timestampToDate(request.getStartTime()));
        togetherModel.setEndTime(DateUtils.timestampToDate(request.getEndTime()));
        togetherModel.setCreateTime(new Date());
        mapper.insertModel(togetherModel);
        response.addResultData("model", convertModel(togetherModel));
        return response;
    }

    @Override
    public Response list(TogetherRequest request) throws Exception {
        Response response = new Response();
        // 分页
        PageObject po = new PageObject();
        po.setCurrPage(request.getPageNum());
        po.setPageSize(request.getPageSize());

        Long startTime = request.getSearchStartTime();
        if (startTime != null) {
            po.addCondition("searchStartTime", DateUtils.timestampToDate(startTime));
        }
        Long endTime = request.getSearchEndTime();
        if (endTime != null) {
            po.addCondition("searchEndTime", DateUtils.timestampToDate(endTime));
        }
        RowBounds rowBounds = new RowBounds(po.getOffset(), po.getPageSize());
        List<TogetherModel> list = mapper.getList(po.getCondition(), rowBounds);
        response.addResultData("list", convertList(list));
        return response;
    }

    @Override
    public Response detail(TogetherRequest request) throws Exception {
        Integer id = request.getId();
        // 约伴信息
        TogetherModel togetherModel = findById(id);
        if (togetherModel == null) {
            return Response.FAILED("约伴已被删除。");
        }
        TogetherResponse togetherResponse = convertModel(togetherModel);
        // 评论列表
        List<TogetherCommentResponse> commentList = commentList(request);

        Response response = new Response();
        response.addResultData("detail", togetherResponse);
        response.addResultData("commentList", commentList);
        return response;
    }

    @Override
    public Response comment(TogetherRequest request) throws Exception {
        String content = request.getContent();
        Integer togetherId = request.getId();
        Integer userId = request.getUserId().intValue();
        Integer replyedId = request.getReplyedid();

        TogetherCommentModel commentModel = new TogetherCommentModel();
        commentModel.setCreateTime(new Date());
        commentModel.setTogetherId(togetherId);
        commentModel.setUserid(userId);
        commentModel.setContent(content);
        commentModel.setReplyedid(replyedId);
        commentMapper.insertModel(commentModel);
        Response response = Response.SUCCESS();
        response.addResultData("comment", commentModel);


        TogetherModel model = findById(togetherId);
        if (model != null) {
            UserModel user = userService.findById(model.getCreateId());
            Map<String, Object> data = new HashMap<>();
            // 用户头像
            data.put("userIcon", user.getPic());
            // 用户昵称
            data.put("userName", user.getNick());
            String images = model.getImages();
            String img = "";
            if (StringUtils.isNotBlank(images)) {
                if (images.contains(",")) {
                    img = images.split(",")[0];
                } else {
                    img = images;
                }
            }
            //图片
            data.put("img", img);
            //时间
            data.put("time", DateUtils.dateToTimestamp(null));
            //内容
            data.put("content", content);
            //1、动态，2、约伴
            data.put("type", 2);
            data.put("id", togetherId);
            //通知类型
            data.put("action", PushType.COMMENT.getValue());

            // 评论动态推送
            SpringUtils.publishEvent(new PushToUserEvent("评论约伴推送...", model.getCreateId(), data));
            if (replyedId != null) {
                SpringUtils.publishEvent(new PushToUserEvent("评论约伴推送...", replyedId, data));
            }
        }
        return response;
    }

    @Override
    public Response myTogether(TogetherRequest request) throws Exception {
        Response response = new Response();
        Integer targetId = request.getTargetId();
        if (targetId == null) {
            targetId = request.getUserId().intValue();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("createId", targetId);
        // 分页
        PageObject po = new PageObject();
        po.setCurrPage(request.getPageNum());
        po.setPageSize(request.getPageSize());
        RowBounds rowBounds = new RowBounds(po.getOffset(), po.getPageSize());
        List<TogetherModel> list = mapper.getList(map, rowBounds);
        response.addResultData("list", convertList(list));
        return response;
    }

    @Override
    public Response delete(TogetherRequest request) throws Exception {
        mapper.deleteById(request.getId());
        return new Response();
    }

    @Override
    public List<TogetherResponse> convertList(List<TogetherModel> list) throws Exception {
        List<TogetherResponse> responseList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (TogetherModel model : list) {
                responseList.add(convertModel(model));
            }
        }
        return responseList;
    }

    private TogetherResponse convertModel(TogetherModel model) {
        TogetherResponse response = null;
        if (model != null) {
            response = new TogetherResponse();
            response.setId(model.getId());
            response.setName(model.getName());
            response.setContent(model.getContent());
            response.setAddress(model.getAddress());
            response.setStartTime(DateUtils.dateToTimestamp(model.getStartTime()));
            response.setEndTime(DateUtils.dateToTimestamp(model.getEndTime()));
            response.setCreateTime(DateUtils.dateToTimestamp(model.getCreateTime()));
            response.setCreateId(model.getCreateId());
            response.setUser(model.getUser());
            response.setImages(model.getImages());
        }
        return response;
    }

    private List<TogetherCommentResponse> commentList(TogetherRequest request) throws Exception {
        Integer togetherId = request.getId();
        // 分页
        PageObject po = new PageObject();
        po.setCurrPage(request.getPageNum());
        po.setPageSize(request.getPageSize());
        RowBounds rowBounds = new RowBounds(po.getOffset(), po.getPageSize());
        po.addCondition("togetherId", togetherId);
        // 查询评论列表
        List<TogetherCommentModel> list = commentMapper.findModelsByCondition(po.getCondition(), rowBounds);
        List<TogetherCommentResponse> commentResponseList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            TogetherCommentResponse response = null;
            for (TogetherCommentModel model : list) {
                response = new TogetherCommentResponse();
                response.setId(model.getId());
                response.setContent(model.getContent());
                response.setNick(model.getNick());
                response.setPic(model.getPic());
                response.setReplyedid(model.getReplyedid());
                response.setReplyedNick(model.getReplyedNick());
                response.setTogetherId(model.getTogetherId());
                response.setUserid(model.getUserid());
                response.setCreateTime(model.getCreateTime());
                response.setCommentCreateTime(DateUtils.dateToTimestamp(model.getCreateTime()));
                commentResponseList.add(response);
            }
        }
        return commentResponseList;
    }
}
